package com.jstide.credit.data.service.db;

import cn.hutool.core.util.StrUtil;
import org.iq80.leveldb.DB;
import org.iq80.leveldb.DBFactory;
import org.iq80.leveldb.Options;
import org.iq80.leveldb.WriteBatch;
import org.iq80.leveldb.impl.Iq80DBFactory;

import java.io.File;
import java.io.IOException;
import java.util.Map;

/**
 * @author SangLiang on 2019-08-23.
 * @version 1.0
 */

public class LevelDBContext<K,V> {

   // private static final org.slf4j.Logger logger = LoggerFactory.getLogger(LevelDBContext.class);

    private static   DBFactory factory = new Iq80DBFactory();
    private static DB db;

    static {
        Options options = new Options();
        options.createIfMissing(true);
        String folder ="dryad.db";
        try {
            db= factory.open(new File(folder), options);
        } catch (IOException e) {
            //logger.error("dryad.db初始化失败",e);
            System.out.println(StrUtil.format("dryad.db初始化失败,{}",e));
        }
    }


    public static void add( String key, String value){
        db.put(Iq80DBFactory.bytes(key), Iq80DBFactory.bytes(value));
    }

    public static String get(String key){
        byte[] bytes = db.get(Iq80DBFactory.bytes(key));
        String value = Iq80DBFactory.asString(bytes);
        return value;
    }

    public static void delete(String key){
        db.delete(Iq80DBFactory.bytes(key));
    }


    public static void  batchAdd2(Map<String,String> kvMap){
        for(Map.Entry<String,String> kv : kvMap.entrySet()) {
            add(kv.getKey(), kv.getValue());
        }
    }

    public static void  batchAdd(Map<String,String> kvMap){
        WriteBatch batch = db.createWriteBatch();
        for(Map.Entry<String,String> kv : kvMap.entrySet()) {
            batch.put(Iq80DBFactory.bytes(kv.getKey()), Iq80DBFactory.bytes(kv.getValue()));
        }
        db.write(batch);
    }

    public static void shutdown(){
        try {
            db.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



}
